import { parse } from 'querystring';
import { array } from 'prop-types';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = path => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);




/**
 * 创建并下载文件 防止 闪烁
 * @param  {String} fileName 文件名
 * @param  {String} url  文件下载地址
 */
export function createAndDownloadFile(url, fileName) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  //设置请求头参数的方式,如果没有可忽略此行代码
  xhr.setRequestHeader("Authorization", 'Bearer ' + sessionStorage.getItem("idToken"));
  //设置响应类型为 blob
  xhr.responseType = 'blob';
  //关键部分
  xhr.onload = function (e) {
    //如果请求执行成功
    if (this.status == 200) {
      var blob = this.response;
      var a = document.createElement('a');
      // blob.type = "application/octet-stream";
      var url = window.URL.createObjectURL(blob);
      if (window.navigator.msSaveBlob) {
        try {
          window.navigator.msSaveBlob(blob, decodeURIComponent(xhr.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]))
        } catch (e) {
          console.log(e);
        }
      } else {
        a.href = url;
        a.download = decodeURIComponent(xhr.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]);
        document.body.appendChild(a); // 火狐浏览器 必须把元素插入body中
        a.click();
        document.body.removeChild(a);
        //释放之前创建的URL对象
        window.URL.revokeObjectURL(url);
      }
    }
  };
  //发送请求
  xhr.send();
}

/**
 * 判断 关系添加是否重复
 * @param  {String} initArr 原始数组
 * @param  {String} item  呆判定元素
 */
export function getInputRelations(fromLabels, toLabels, labelRelationName) {
  let relations = [];
  fromLabels.forEach(labelFromName => {
    toLabels.forEach(labelToName => {
      relations.push({ labelFromName, labelRelationName, labelToName });
    });
  });
  return relations;
}

/**
 * 判断 关系添加是否重复
 * @param  {String} initArr 原始数组
 * @param  {String} item  呆判定元素
 */
export function relationRedo(relations, inputRelations) {
  let isRedo = false;
  // eslint-disable-next-line max-len
  const relationList = relations.map(relation => `${relation.labelFromName}_${relation.labelRelationName}_${relation.labelToName}`);
  inputRelations.forEach(inputRelation => {
     if (relationList.indexOf(`${inputRelation.labelFromName}_${inputRelation.labelRelationName}_${inputRelation.labelToName}`) > -1) {
       isRedo = true;
     }
    });
  return isRedo;
}

/**
 * 判断 关系添加是否重复
 * @param  {String} initArr 原始数组
 * @param  {String} item  呆判定元素
 */
export function relationNotExists(objectLabels, propLabels, fromLabels, toLabels, isProp) {
  let notExists = false;
  const propList = propLabels.map(a => a.labelName);
  const objectList = objectLabels.map(a => a.labelName);
  const toList = [...toLabels];
    const fromList = [...fromLabels];
    fromList.forEach(val => {
      if (objectList.indexOf(val) === -1) {
        notExists = true;
      }
    });

    toList.forEach(toLabel => {
      if ((!isProp && objectList.indexOf(toLabel) === -1) ||
        (isProp && propList.indexOf(toLabel) === -1)) {
        notExists = true;
      }
    });
  return notExists;
}

/**
 * 给已经添加的关系添加 标识符
 * @param  {String} initArr 原始数组
 */
export function relationAddFlag(initArr) {
  initArr.map(val => {
    val['isSave'] = true;
  })
  return initArr;
}

export function createUUID() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid.replace(/\-/g, '');
}


/**
 * 上传文件前校验
 * @param  {String} file 文件名
 * @param  {Array} accept 允许得文件名数组
 */
export function checkBeforeFileUpload(file, accept) {
  // 函数式
  // return new Promise((resolve, reject) => {
  //   let fileName = file.name;
  //   let index = fileName.lastIndexOf(".");
  //   let suffix = fileName.substr(index + 1);

  //   if (accept.indexOf(suffix) === -1) {
  //     return reject(false)
  //   }
  //   return resolve(true);
  // });

  // 直接返回布尔值
  let fileName = file.name;
  let index = fileName.lastIndexOf(".");
  let suffix = fileName.substr(index + 1);
  if (fileName.length > 64) {
    return { tip: false, msg: '文件名太长' }
  }
  if (file.size > 100 * 1024 * 1024) {
    return { tip: false, msg: '文件最大100MB' }
  }
  if (accept.indexOf(suffix) === -1) {
    return { tip: false, msg: '不支持该类型文件' }
  }
  return { tip: true, msg: '' }
}
/**
 * @description 改写 websocket url
 * @param {string} url
 */
export const rewriteUrlToSocket = (url) => {
  const replaceProtocol = (url) => url.replace(/^http/, 'ws').replace(/^https/, 'wss');
  if(!url) return url;
  if(replaceProtocol(url).search(/^ws[s]{0,1}/)!==-1) return replaceProtocol(url);
  if(window) {
    const { protocol, host} = window.location;
    return `${replaceProtocol(protocol)}//${host}${url}`;
  }
  return url;
}
